package com.ikas.ai.server.module.system.service;

import com.google.code.kaptcha.Producer;
import com.ikas.ai.consts.Consts;
import com.ikas.ai.server.error.BusinessException;
import com.ikas.ai.utils.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.awt.image.BufferedImage;

/**
 * @author deng.baohui
 * 图片验证码处理类
 */
@Service
public class CaptchaService {

    @Autowired
    private Producer producer;
    @Autowired
    private RedisUtil redisUtils;


    /**
     * 获取图片流
     *
     * @param uuid
     * @return
     */
    public BufferedImage getCaptcha(String uuid) {
        //生成文字验证码
        String code = producer.createText();
        //存入redis中 5分钟后过期
        redisUtils.saveBean(Consts.CAPTCHA_KEY + uuid, code, Consts.CAPTCHA_KEY_TIMEOUT);
        return producer.createImage(code);
    }

    /**
     * 校验验证码是否正确
     *
     * @param uuid
     * @param code
     * @return
     */
    public void validate(String uuid, String code) {
        if (StringUtils.isBlank(uuid)) {
            throw new BusinessException("验证码uid为空");
        }
        //获取redis验证码
        String capCode = redisUtils.getBean(Consts.CAPTCHA_KEY + uuid, String.class);
        if (StringUtils.isBlank(capCode)) {
            throw new BusinessException("验证码已失效");
        }
        //校验redis中验证码和输入验证码是否一致
        if (!code.equalsIgnoreCase(capCode)) {
            //从redis缓存中删除验证码
            redisUtils.deleteKey(Consts.CAPTCHA_KEY + uuid);
            throw new BusinessException("验证码错误");
        }
        //从reids缓存中删除验证码
        redisUtils.deleteKey(Consts.CAPTCHA_KEY + uuid);
    }
}
